package com.leicx.guli.search.service.impl;

import cn.hutool.json.JSONUtil;
import com.leicx.guli.common.to.es.SkuEsModel;
import com.leicx.guli.search.config.EsConfig;
import com.leicx.guli.search.constant.EsConstant;
import com.leicx.guli.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author daxiong
 * @date 2021/7/26 下午8:33
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> esModels) throws IOException {
        // 保存到es
        // 1.给es中建立索引
        BulkRequest bulkRequest = new BulkRequest(EsConstant.PRODUCT_INDEX);
        esModels.forEach(q -> {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(q.getSkuId().toString());
            String jsonStr = JSONUtil.toJsonStr(q);
            indexRequest.source(jsonStr, XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        // 2.给es中保存这些数据
        BulkResponse response = restHighLevelClient.bulk(bulkRequest, EsConfig.COMMON_OPTIONS);
        boolean hasFailures = response.hasFailures();
        return !hasFailures;
    }
}
